package com.heima.statics.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.heima.aliyun.oss.AliyunOssTemplate;
import com.heima.common.exception.LogicException;
import com.heima.model.aritlce.dto.ArticleDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.statics.service.ArticleStaticService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@Service
public class ArticleStaticServiceImpl implements ArticleStaticService {

    @Resource
    private Configuration configuration;

    @Resource
    private AliyunOssTemplate aliyunOssTemplate;

    /**
     * 静态页生成方法
     *
     * @param id
     * @param dto
     * @return
     */
    @Override
    public String buildArticleHtml(Long id, ArticleDto dto) {
        try {
            // 1 定义数据模型
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("content", JSONUtil.parseArray(dto.getContent()));
            dto.setContent(null);
            dataModel.putAll(BeanUtil.beanToMap(dto, false, true));
            // 2 加载模板
            Template template = configuration.getTemplate("article.ftl");
            // 3 生成页面
            StringWriter writer = new StringWriter();
            template.process(dataModel, writer);
            // 4 将静态HTML页面保存到本地
            String fileName = id + ".html";
            String filePath = saveToLocal(fileName, writer.toString());
            // fileName 前面拼接 localhost:85/
            String url = "http://localhost:85/" + fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LogicException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * 将HTML内容保存到本地文件
     *
     * @param fileName 文件名
     * @param content  文件内容
     * @return 文件的访问路径
     */
    private String saveToLocal(String fileName, String content) {
        FileWriter fileWriter = null;
        try {
            // 指定保存在 nginx-hmtt\\html 目录下
            Path desktopPath = Paths.get("..\\nginx-hmtt\\html");
            // 确保目录存在
            if (!Files.exists(desktopPath)) {
                Files.createDirectories(desktopPath);
            }

            // 完整文件路径
            Path filePath = desktopPath.resolve(fileName);

            // 写入文件
            fileWriter = new FileWriter(filePath.toFile());
            fileWriter.write(content);
            fileWriter.flush();

            // 返回文件的访问路径
            return filePath.toString().replace("\\", "/");
        } catch (IOException e) {
            e.printStackTrace();
            throw new LogicException(AppHttpCodeEnum.SERVER_ERROR);
        } finally {
            // 确保文件流正确关闭
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
